import { encrypt } from './encryption';

export const uuidv4 = () => {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        let r = (Math.random() * 16) | 0,
            v = c == 'x' ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
};

export const rankParams = (data) => {
    const keyArr = Object.keys(data).sort();
    const obj = {};
    keyArr.forEach((key) => {
        obj[key] = data[key];
    });
    return JSON.stringify(obj);
};

/**
 * 用于post 方式的请求 签名
 */
export const getSign = (pk, data) => {
    // console.log(rankParams(data))
    // console.log(encrypt(rankParams(data), pk))
    // console.log(toBase64(encrypt(rankParams(data), pk)))
    return toBase64(encrypt(rankParams(data), pk));
};

export const qsifyParams = (data) => {
    const keyArr = Object.keys(data);
    const len = keyArr.length;
    return keyArr.reduce((p, c) => {
        return `${p}${c}=${data[c]}${c === keyArr[len - 1] ? '' : '&'}`;
    }, '');
};
/**
 * 用于get 方式的请求 签名,
 * 无需将参数排序
 */
export const getSignOfGetMethod = (pk, data) => {
    // console.log('qsifyParams(data): ', qsifyParams(data));
    return toBase64(encrypt(qsifyParams(data), pk));
};

export const toBase64 = (str) => {
    return btoa(str);
};

export const Platform = {
    isAndroid: () => {
        return /(android)/gi.test(navigator.userAgent);
    },
    isiOS: () => {
        return /(iPhone|iPad|iPod|iOS)/gi.test(navigator.userAgent);
    },
};
